package com.labofjet.web.bean.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.labofjet.exception.BaseException;
import com.labofjet.exception.BusinessException;
import com.labofjet.web.bean.ContextDTO;

/**
 * 用于前后台数据交互时候格式的统一
 * 
 * @author jyzjyz12@163.com
 * 
 */
public class JsonContextDTO implements ContextDTO {
    private static final ObjectMapper OM;
    private static final Logger LOGGER = LoggerFactory.getLogger(JsonContextDTO.class);

    static {
        OM = new ObjectMapper();
        OM.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);// java没有json的某些字段不报错
    }

    private String stateCode;
    private BaseException exception;
    private JsonNode rootNode;// js->java, 读取ajax post上传上来的最外层data
    private Map<String, Object> data = new HashMap<String, Object>();// java->js, 往JS写数据的时候用

    public BaseException getException() {
        return exception;
    }

    public void setException(BaseException exception) {
        this.exception = exception;
    }

    public String getStateCode() {
        return stateCode;
    }

    public void setStateCode(String stateCode) {
        this.stateCode = stateCode;
    }

    public JsonNode getRootNode() {
        return rootNode;
    }

    public void setRootNode(JsonNode rootNode) {
        this.rootNode = rootNode;
    }

    public Map<String, Object> getData() {
        return data;
    }

    public void setData(Map<String, Object> data) {
        this.data = data;
    }

    @Override
    public <T> T getDto(String fieldName, Class<T> dtoClass) {
        try {
            JsonNode dataNode = rootNode.findValue("data");
            return OM.treeToValue(dataNode.findValue(fieldName), dtoClass);
        } catch (JsonProcessingException e) {
            LOGGER.error("解析json错误", e);
            throw new BusinessException(null, "请求参数解析错误");
        }
    }

    @Override
    public void putData(String key, Object value) {
        data.put(key, value);
    }

    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }
}
